﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace LinWon.Core
{
    /// <summary>
    /// 分页
    /// </summary>
    public class PageHelper
    {        
        /// <summary>
        /// 获得分页SQL(sqlserver2005)
        /// </summary>
        /// <param name="sql">表名或查询语句,查询语句需要加()</param>
        /// <param name="startRowIndex">开始索引</param>
        /// <param name="maximumRows">最大记录数</param>
        /// <returns></returns>
        /// 
        public static string GetPageSqlBySqlSever(string sql, int startRowIndex, int maximumRows)
        {

            if (maximumRows == 0)
                maximumRows = int.MaxValue;

            string tmp = sql.ToLower().Substring(sql.IndexOf("(") + 1, sql.LastIndexOf(")") - sql.IndexOf("(") - 1);

            string orderStr = ReturnOrderByString(ref tmp);

            if (string.IsNullOrEmpty(orderStr))
                orderStr = @"order by (select 1)";
            //{0}表名或查询语句,查询语句需要加()
            //{1}结束索引
            //{2}开始索引
            string sqlFormat = "select * from ( select *, ROW_NUMBER() OVER({0}) as rowNum  from ({1}) as pageTable) as T where T.rowNum>{2} and T.rowNum<={3} ";

            return string.Format(sqlFormat, orderStr, tmp, startRowIndex, startRowIndex + maximumRows);
        }

        public static string ReturnOrderByString(ref string str)
        {
            int stk = 0;
            Regex r = new Regex(@"order[ ]+by");

            int index = str.IndexOf('(');
            string odstr = "";
            if (index <= 0)
            {
                if (str.IndexOf(')') > 0)
                    throw new Exception("括弧不配对");
                else
                {
                    if (r.IsMatch(str))
                    {
                        odstr = r.Match(str).Groups[0].Value;
                        index = str.IndexOf(odstr);
                        odstr = str.Substring(index);
                        str = str.Substring(0, index);
                        return odstr;

                    }
                    //else
                    //    throw new Exception("语法错误");
                }
            }
            string tmp = str.Substring(index + 1);

            stk = 1 ;

            for (int i = 0; i < tmp.Length; i++)
            {
                if (tmp[i] == '(')
                    stk++;
                if (tmp[i] == ')')
                {
                    stk--;

                    if(stk<0) throw new Exception("括弧不配对");
                    
                    if (stk == 0)
                    {
                        tmp = tmp.Substring(i + 1);
                        odstr = ReturnOrderByString(ref tmp);
                        str = str.Substring(0, index + 2 + i) + tmp;
                        break;
                    }
                }
            }
            return odstr;
        }
    }
}
